package br.edu.curso.java.refatorar;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.edu.curso.java.VO.IVO;
import br.edu.curso.java.dao.BaseHibernate;

public class ProfessorDAO  {
    
	private Session session;

	public void incluir(IVO p) {
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			session.save(p);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}

	public void alterar(IVO p) {
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			session.update(p);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
		}finally{
			session.close();
		}
	}
	
	public void excluir(ProfessorVO p) {
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			session.delete(p);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
		}finally{
			session.close();
		}
	}

	public ProfessorVO retornar(int codigo) {
		ProfessorVO retorno = new ProfessorVO();
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			retorno = (ProfessorVO) session.get(ProfessorVO.class, codigo);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
		}finally{
			session.close();
		}
		return retorno;
	}

	@SuppressWarnings("unchecked")
	public List<IVO> listar() {
		List<IVO> lista = new ArrayList<IVO>();
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			lista = (List<IVO>) session.createCriteria(ProfessorVO.class).list();
			session.getTransaction().commit();
		} catch (Exception e) {			
			session.getTransaction().rollback();
		}finally{
			session.close();
		}
		
		return lista;
	}

	@SuppressWarnings("unchecked")
	public List<ProfessorVO> listar(ProfessorVO professor) {
		Criteria c = session.createCriteria(ProfessorVO.class);
		if (professor.getNome().length() > 0) {
			c.add(Restrictions.like("nome", professor.getNome() + "%"));
		}
		c.addOrder(Order.asc("descricao"));
		return (List<ProfessorVO>) c.list();
	}

	
}